package kotan.view.table;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JOptionPane;

import kotan.datastore.api.Blob;
import kotan.datastore.api.Text;
import kotan.view.table.editor.BlobEditDialog;
import kotan.view.table.editor.KeyEditorDialog;
import kotan.view.table.editor.TextEditorDialog;

class EntityTableControl {
    
    /** logger */
    private static Logger logger = Logger.getLogger(EntityTableControl.class.getName());

    private final EntityTableView view;

    EntityTableControl(EntityTableView view) {
        this.view = view;
    }

    void editSpecialColumn(int tableRow, int tableColumn) {
        if (logger.isLoggable(Level.FINE)) logger.fine("editColumn: " + tableRow + "," + tableColumn);
        int row = view.table.convertRowIndexToModel(tableRow);
        int column = view.table.convertColumnIndexToModel(tableColumn);
        // New Entity Row
        if (view.tableModel.isCreateRow(row)) {
            if (logger.isLoggable(Level.FINE)) logger.fine("entity create");
            KeyEditorDialog.showDialog(view.table, view.tableModel.getKind(), view.tableModel.getKey(row));
        } else {
            Object value = view.tableModel.getValueAt(row, column);
            if (value == null) setDefaultValueAt(row, column);
            if (view.tableModel.isKey(column)) {
                KeyEditorDialog.showDialog(view.table, view.tableModel.getKind(), view.tableModel.getKey(row));
            } else if (value instanceof Text) {
                TextEditorDialog.showDialog(view.table, view.tableModel.get(row), column, (Text) value);
            } else if (value instanceof Blob) {
                BlobEditDialog.show(view.table, view.tableModel.get(row), column);
            } else {
                JOptionPane.showMessageDialog(
                    view.table,
                    "Sorry, do you want support this type? ",
                    "Unspported Type",
                    JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }

    void createNewEntity() {
        KeyEditorDialog.showCreateDialog(view.table, view.tableModel.getKind());
    }

    void setNullAt(int row, int col) {
        view.tableModel.setValueAt(null, row, col);
    }

    void setDefaultValueAt(int row, int col) {
        view.tableModel.setDefaultValueAt(row, col);
    }

}
